import loginApi from '../../api/sys'
import md5 from 'js-md5'
import storage from '../../utils/storage'
import auth from '../../utils/auth'
import router from '../../router/index'

export default {
    state: {
        token: storage.getItem('token') || '',
        userInfo: storage.getItem('userInfo') || '',
    },
    mutations: {
        saveToken(state, token) {
            state.token = token
            storage.setItem('token', token)
        },
        saveUserInfo(state, userInfo) {
            state.userInfo = userInfo
            storage.setItem('userInfo', userInfo)
        },
    },
    actions: {
        doLogin({ commit }, loginForm) {
            let { username, password } = loginForm
            return new Promise((resolve, reject) => {
                loginApi.doLogin(username, md5(password)).then((res) => {
                    // console.log(res);
                    commit('saveToken', res.token);
                    auth.setTimeStamp();
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        getUserInfo({ commit }) {
            return new Promise((resolve, reject) => {
                loginApi.getUserInfo().then((res) => {
                    // console.log(res);
                    commit('saveUserInfo', res);
                    auth.setTimeStamp();
                    resolve(res)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        getOut({ commit }) {
            commit('saveToken', null)
            commit('saveUserInfo', null)
            storage.removeItem('token')
            storage.removeItem('userInfo')
            // this.$message.success({
            //     message: '退出成功',
            //     offset: 80,
            // })
            router.push('/login')
        }
    }
}
